package com.example.sangong.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

public class MyExcelUtils {

    private static <E> void writeData(OutputStream outputStream, List<E> dataList, Class<E> eClass, String sheetName) {
        EasyExcel.write(outputStream)
                .head(eClass)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet(sheetName)
                .doWrite(dataList);
    }

    public static <E> void writeData(HttpServletResponse response, List<E> dataList, Class<E> eClass, String fileName) {
        try (OutputStream outputStream = response.getOutputStream()) {
            setExcelResponseProp(response, fileName);
            writeData(outputStream, dataList, eClass, fileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <E> List<E> readData(MultipartFile file, Class<E> eClass) {
        try (InputStream ins = file.getInputStream()) {
            return EasyExcel.read(ins)
                    .head(eClass)
                    .sheet()
                    .doReadSync();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 设置响应结果
     *
     * @param response    响应结果对象
     * @param rawFileName 文件名
     * @throws UnsupportedEncodingException 不支持编码异常
     */
    private static void setExcelResponseProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }
}
